class ToolsController < ApplicationController
  require "rexml/document"

  #
  #   show skillup page
  #
  def start_skillup
    @course_id = params[:course_id]
  end

  #
  #   get couser and return xml
  #
  def get_course
    #init
    course_id = params[:id]
    course = Course.get_single_course_and_info(course_id)
    author = course.user

    doc = create_xml
    root = add_root_element doc

    #添加list及属性
    ele_course = root.add_element("course")
    # course id
    ele_course_id = ele_course.add_element("CourseID")
    ele_course_id.add_text(course.id.to_s)
    # course title
    ele_course_title = ele_course.add_element("CourseTitle")
    ele_course_title.add_text(REXML::CData.new(course.title))
    # course description
    ele_course_desc = ele_course.add_element("CourseDesc")
    ele_course_desc.add_text(REXML::CData.new(course.description))
    # course RecommendedCoursePeriod
    # not added
    # cueLanguageCode
    ele_course_cue_lan =  ele_course.add_element("CueLanguageCode")
    ele_course_cue_lan.add_text("ja")

    ele_course_cue_lan =  ele_course.add_element("ResponseLanguageCode")
    ele_course_cue_lan.add_text("zh_cn")
    # course icon
    ele_course_icon = ele_course.add_element("Icon")
    ele_course_icon.add_text(REXML::CData.new(get_course_image_url(course)))

    # course total items count
    ele_total_items = ele_course.add_element("TotalItems")
    ele_total_items.add_text(course.items_count.to_s)

    # course author info
    ele_author = ele_course.add_element("author")
    ele_author.add_attribute("id", author.id.to_s)
    ele_name = ele_author.add_element("name")
    ele_name.add_text(REXML::CData.new(author.nickname))
    ele_author_icon = ele_author.add_element("icon")
    ele_author_icon.add_text(REXML::CData.new(get_user_image_url(author)))

    # Add personal data

    if user_login?
      user_id = current_user.id
      course_id = course.id

      #init user study course info
      study_course_log = UserCourse.user_learned_course(user_id,course_id)
      
      #init user study item data
      weak_items_count = UserItem.user_weak_items_count(user_id, course_id)    # it means  item's persatage <= 50%
      strong_items_count  = UserItem.user_strong_items_count(user_id, course_id)    # it means  item's persatage > 50%
      completed_items_count = UserItem.user_completed_item_count(user_id, course_id) # it means  item's persatage = 100%
      new_items_count = UserItem.user_new_items_count(completed_items_count,weak_items_count+strong_items_count,course)

      # course completed  flag
      ele_completed_flag = ele_course.add_element("CourseCompleted")
      study_course_log.progress==100 ? ele_completed_flag.add_text("True") : ele_completed_flag.add_text("False")
      # course started time
      ele_start_time = ele_course.add_element("CourseStartDate")
      ele_start_time.add_text(study_course_log.created_at.to_date.to_s)
      # course total study time
      # it is valued by  millisecond, 1000 millisecond == 1 second
      ele_total_time = ele_course.add_element("TotalStudyTime")
      ele_total_time.add_text(study_course_log.sessiontime.to_s)
      # course end time
      ele_total_time = ele_course.add_element("StudyEndDate")
      ele_total_time.add_text(study_course_log.updated_at.to_date.to_s)
      # course progress
      ele_course_progress = ele_course.add_element("CourseProgress")
      ele_course_progress.add_text(study_course_log.progress.to_s)
      # StrictSpelling ,ShowStrictSpellingSettings ,ShowImageSettings ,PlayResponseSound,UseOpenEndDate
      # NewItems
      ele_new_items = ele_course.add_element("NewItems")
      ele_new_items.add_text(new_items_count.to_s)
      # WeakItems , it means  item's persatage < 50%
      ele_weak_items = ele_course.add_element("WeakItems")
      ele_weak_items.add_text(weak_items_count.to_s)
      # StrongItems , persatage > 50%
      ele_strong_items = ele_course.add_element("StrongItems")
      ele_strong_items.add_text(strong_items_count.to_s)
      # CompletedItems
      ele_completed_items = ele_course.add_element("CompletedItems")
      ele_completed_items.add_text(completed_items_count.to_s)

      # SkippedItems
      #        ele_skipped_items = ele_course.add_element("SkippedItems")
      #        ele_skipped_items.add_text("23")
      # ScheduleMessage
    end
    render :xml=>doc
  rescue
    render :text => "" ,:status=>500
  end

  # it will return  some items  to study, we will descript it with  xml below:
  def get_study_data
    course_id = params[:id]
    # xml begin:
    doc = create_xml
    root = add_root_element doc

    #添加list Element
    ele_items = root.add_element("items")
    # 通过 For 循环 产生 学习单元的xml描述

    items = []
    if user_login?
      #login user's items, include study info
      items = Item.get_study_items_words(course_id,current_user.id)
    else
      #not login user's items
      items = Item.get_study_items_words_not_user(course_id)
    end
    items.each  do |item|
      ele_item = ele_items.add_element("item")
      # add language attribute of item == ours is just  janpanese now
      ele_item.add_attribute("language" , "janpanese")
      # add  id attribute of item  to iditifiy one item
      ele_item.add_attribute("id" , item.id.to_s)
      # add href attribute to item ,  for example: http://damanzu.com/items/12
      ele_item.add_attribute("href" , $index_server_url+"/items/"+item.id.to_s)
      #
      # now ,begin to add  study target to item: like  kana , kanji , chractor
      # we add these attributes to element cue , cue means  "字母"
      ele_cue = ele_item.add_element("cue")
      # set cue's text, like  kana
      ele_text = ele_cue.add_element("text")
      ele_text.add_text(REXML::CData.new(item.kana))
      # set cue's charactor
      ele_text = ele_cue.add_element("charactor")
      ele_text.add_text(REXML::CData.new(item.kanji))
      # set cue's pos
      ele_text = ele_cue.add_element("pos")
      ele_text.add_text(REXML::CData.new(item.pos))
      # set cue's sound href
      ele_text = ele_cue.add_element("sound")
      unless item.audio_path.blank?
        ele_text.add_text(REXML::CData.new($assers_server_url+item.audio_path))
      else
        ele_text.add_text("")
      end
      # cue end
      #
      # responses begin
      ele_responses = ele_item.add_element("responses")
      ele_response = ele_responses.add_element("response")
      # set response's meaning attribute
      ele_response.add_attribute("type","meaning")
      ele_response.add_attribute("language","chinese")
      ele_response_text = ele_response.add_element("text")
      ele_response_text.add_text(REXML::CData.new(item.translation))
      # add quizzes element
      ele_quizzes = ele_response.add_element("quizzes")
      # add one quiz , if  there are many quizzes  , for ..each
      ele_quiz = ele_quizzes.add_element("quiz")
      ele_quiz.add_attribute("type", "multiple_choice")
      ele_question = ele_quiz.add_element("question")
      ele_question.add_text(REXML::CData.new(item.kana))
      ele_answer = ele_quiz.add_element("answer")
      ele_answer.add_text(REXML::CData.new(item.translation))
      ele_distractors = ele_quiz.add_element("distractors")
      ele_distractors.add_attribute("type","type")
      #
      # distractors begin
      # for i in (1..5)
      distratcor_items = get_distractor_item(items, item)
      distratcor_items.each do |d_item|
        ele_distractor = ele_distractors.add_element("distractor")
        ele_distractor.add_attribute("item_id",d_item.id.to_s)
        ele_distractor.add_text((REXML::CData.new(d_item.translation)))
      end
      # distractors end

      # spelling quiz
      ele_quiz = ele_quizzes.add_element("quiz")
      ele_quiz.add_attribute("type", "spelling")
      ele_question = ele_quiz.add_element("question")
      ele_question.add_text(REXML::CData.new(item.kanji))
      ele_answer = ele_quiz.add_element("answer")
      ele_answer.add_text(REXML::CData.new(item.kana))
      # quiz end
      # responses end
      #
      # progress begin
      if user_login?
        user_study_item_log = UserItem.user_learned_singal_item(current_user.id, item.id)
        unless user_study_item_log.blank?
          ele_progress = ele_item.add_element("progress")
          ele_progress.add_attribute("skipped", "false")
          ele_progress.add_attribute("percentage", user_study_item_log.progress)
          ele_progress.add_attribute("urgency", "12")
          ele_progress.add_attribute("item_id", item.id.to_s)
        end
      end

      # one item elements  end
    end
    render :xml=> doc
  rescue
    render :text => "" ,:status=>500
  end


  #
  #   update user study items progress
  #
  def update_items_progress
    unless user_login?
      raise "not login"
    end
    user_id = current_user.id
    #   process params
    json_obj = ActiveSupport::JSON.decode(params[:status])
    raise "not status data" if json_obj.nil?
    #   analyse data
    course_id = json_obj["course_id"].to_i
    study_time = json_obj["study_time"].to_i
    study_data = json_obj["study_data"]
    raise "no data" if study_data.nil?
    #   update study item data
    study_data.each do |item_data|
      #   init study item data params
      new_progress = item_data["score"].to_i
      item_id = item_data["item_id"].to_i
      #   get study item log , if not have date ,create it
      user_study_item_log = UserItem.find_or_creatd_study_item_log(user_id,course_id,item_id)
      #   update study item data
      UserItem.update_study_info(user_study_item_log,new_progress)
    end
    # get user study course data, if not have date create it
    user_study_course_data = UserCourse.user_learned_course(user_id, course_id)
    UserCourse.update_study_info(user_study_course_data,study_time)
    #   calculate study course progress
    UserCourse.calculate_progress(user_study_course_data)
    render :text=>""
  rescue
    render :text => "" ,:status=>500
  end

  #
  #   get calendar data
  #
  def get_history
    r_time = params[:request_date]
    data_temp = UserItem.get_useitem_count_by_date(current_user.id, r_time+"-1",r_time+"-31")
    doc = create_xml
    root = add_root_element doc
    calendardata_ele = root.add_element("calendardata")
    calendardata_ele.add_attribute("month",r_time.to_s)
    data_temp.each do |data|
      day_ele = calendardata_ele.add_element("day")
      day_ele.add_attribute("value",data.course_id.to_s)#course_id is day
      day_ele.add_text(data.user_id.to_s)#user_id is items count
    end
    render :text=> doc
  rescue
    render :text=> "",:status=>500
  end

  # user xml
  def get_user
    doc = create_xml
    root = add_root_element doc
    ele_user = root.add_element("user")
    ele_status = ele_user.add_element("status")

    if  user_login?
      user = current_user
      ele_status.add_text("1")
      ele_id = ele_user.add_element("id")
      ele_id.add_text(user.id.to_s)
      ele_nickname = ele_user.add_element("nickname")
      ele_nickname.add_text(user.nickname)
    else
      ele_status.add_text("0")
    end

    render :text=> doc
  rescue
    render :text => "" ,:status=>500
  end

  #
  #   remote user login support
  #
  def remote_user_valid
    user_name =  params[:user_name]
    user_pwd =  params[:password]
    temp_account=Account.authenticate(user_name,user_pwd)
    unless temp_account.blank?
      session[:account_id] =temp_account.id
    end
    get_user
  rescue
    render :text => "" ,:status=>500
  end






  def test
    
  end

  private

  #
  #   build a basic xml
  #
  def create_xml
    REXML::Document.new '<?xml version="1.0" encoding="utf-8" ?>'
  end

  #
  #   add root element for xml
  #
  def add_root_element(document)
    root = document.add_element("root")
    root.add_attributes({"xmlns:dc" => "http://purl.org/dc/elements/1.1/"})
    return root
  end

  #
  #   get distractor item, all item's array exclude current item
  #
  #   @all_item<Array>   all item array
  #
  #
  def get_distractor_item(all_item, current_item)
    temp_array = []
    all_item.each do |item|
      unless item == current_item
        temp_array << item
      end
    end
    temp_array
  end
  

end